from PIL import Image
import cv2
import numpy as np
from figureshow import figure_show
from figurechange import figure_change
from imageconvert import image_convert, image_convert_duibidu

import time

def is_reddish(pixel_rgb):
    red, green, blue = pixel_rgb

    # 设置红色通道较高的阈值
    red_threshold = 230
    # 使红色明显高于其他通道的阈值
    dominance_factor = 50

    # 检查红色通道是否足够高，同时红色要比绿色和蓝色明显高
    if red > red_threshold and (red - green) > dominance_factor and (red - blue) > dominance_factor:
        return True
    return False

def is_whitedish(pixel_rgb):

    # 设置红色通道较高的阈值
    red_threshold = 255
    # 使红色明显高于其他通道的阈值
    dominance_factor = 50
    
    # 0, 0, 0 表示黑色。
    # 255, 255, 255 表示白色。
    # 检查红色通道是否足够高，同时红色要比绿色和蓝色明显高
    if pixel_rgb > 250:
        return True
    # if red == 0 and green == 0 and blue == 0:
        # return True
    return False

def is_blackish(pixel_rgb):
    # 判断黑色像素的阈值
    black_threshold = 25
    if pixel_rgb[0] < 200 and pixel_rgb[1] < black_threshold and pixel_rgb[2] < black_threshold:
        return True
    return False
    
def is_blackish_huidu(pixel_rgb):
    # 判断黑色像素的阈值
    # black_threshold = 25
    # if pixel_rgb[0] < 200 and pixel_rgb[1] < black_threshold and pixel_rgb[2] < black_threshold:
        # return True
    if pixel_rgb == 0:
        return True
    return False

def getXY(filePath, min_pixel_count=50):
    # 打开图片文件
    image = Image.open(filePath)

    # 获取图像的宽度和高度
    width, height = image.size
    print("width, height =", width, height)

    # 初始化存储红点和黑点坐标的列表
    red_pixel_coordinates, black_pixel_coordinates = [], []

    # 遍历图像的每个像素
    white_num = 0
    for y in range(height):
        for x in range(width):
            # 获取像素的RGB值
            pixel_rgb = image.getpixel((x, y))

            # 使用新的红色检测逻辑识别红色及偏红像素
            if is_reddish(pixel_rgb):
                print(pixel_rgb, (x, y))
                red_pixel_coordinates.append((x, y))
                white_num += 1

            # 使用封装好的函数识别黑色像素
            if is_blackish(pixel_rgb):
                black_pixel_coordinates.append((x, y))
    print("red_num =", white_num)
    x_range = (0, width)
    y_range = (0, height)
    figure_show(red_pixel_coordinates, x_range, y_range)
    # 计算红点和黑点的平均坐标，只计算集中的大区域
    if len(red_pixel_coordinates) >= min_pixel_count:
        redX = sum([p[0] for p in red_pixel_coordinates]) / len(red_pixel_coordinates)
        redY = sum([p[1] for p in red_pixel_coordinates]) / len(red_pixel_coordinates)
        red_center = (redX, redY)
    else:
        print("No concentrated red pixels found.")
        red_center = None

    if len(black_pixel_coordinates) >= min_pixel_count:
        blackX = sum([p[0] for p in black_pixel_coordinates]) / len(black_pixel_coordinates)
        blackY = sum([p[1] for p in black_pixel_coordinates]) / len(black_pixel_coordinates)
        black_center = (blackX, blackY)
    else:
        print("No concentrated black pixels found.")
        black_center = None

    return red_center, black_center
    
def getXY_white(filePath, min_pixel_count=50):
    # 打开图片文件
    image = Image.open(filePath)

    # 获取图像的宽度和高度
    width, height = image.size
    print("width, height =", width, height)

    # 初始化存储红点和黑点坐标的列表
    red_pixel_coordinates, black_pixel_coordinates = [], []

    # 遍历图像的每个像素
    white_num = 0
    for y in range(height):
        for x in range(width):
            # 获取像素的RGB值
            pixel_rgb = image.getpixel((x, y))

            if is_whitedish(pixel_rgb):
                print(pixel_rgb, (x, y))
                red_pixel_coordinates.append((x, y))
                white_num += 1

            # 使用封装好的函数识别黑色像素
            if is_blackish_huidu(pixel_rgb):
                black_pixel_coordinates.append((x, y))
    print("white_num =", white_num)
    x_range = (0, width)
    y_range = (0, height)
    figure_show(red_pixel_coordinates, x_range, y_range)
    # 计算红点和黑点的平均坐标，只计算集中的大区域
    min_pixel_count_white = 10
    if len(red_pixel_coordinates) >= min_pixel_count_white:
        redX = sum([p[0] for p in red_pixel_coordinates]) / len(red_pixel_coordinates)
        redY = sum([p[1] for p in red_pixel_coordinates]) / len(red_pixel_coordinates)
        red_center = (redX, redY)
    else:
        print("No concentrated red pixels found.")
        red_center = None

    if len(black_pixel_coordinates) >= min_pixel_count:
        blackX = sum([p[0] for p in black_pixel_coordinates]) / len(black_pixel_coordinates)
        blackY = sum([p[1] for p in black_pixel_coordinates]) / len(black_pixel_coordinates)
        black_center = (blackX, blackY)
    else:
        print("No concentrated black pixels found.")
        black_center = None

    return red_center, black_center
    
def get_white_points(filePath):
    # 打开图片文件
    image = Image.open(filePath)
    # 获取图像的宽度和高度
    width, height = image.size
    white_point_list = []
    # 遍历图像的每个像素
    white_num = 0
    for y in range(height):
        white_points = list()
        for x in range(width):
            # 获取像素的RGB值
            pixel_rgb = image.getpixel((x, y))

            if is_whitedish(pixel_rgb):
                white_points.append((x, y))
                white_num += 1
        if white_points:
            white_point_list.append([white_points[0], white_points[-1]])
    print("white_num =", white_num)
    return white_point_list, width, height
    
def sort_white_points(white_point_list, width, height):
    points_show = list()
    for white_point in white_point_list:
        points_show.append(white_point[0])
    for white_point in white_point_list[::-1]:
        points_show.append(white_point[1])
    x_range = (0, width)
    y_range = (0, height)
    figure_show(points_show, x_range, y_range)

def get_outer_points(filePath):
    
    # 打开图片文件
    image = Image.open(filePath)
    # 获取图像的宽度和高度
    width, height = image.size
    coordinates = []
    # 遍历图像的每个像素
    for y in range(height):
        for x in range(width):
            # 获取像素的RGB值
            pixel_rgb = image.getpixel((x, y))

            if is_whitedish(pixel_rgb):
                coordinates.append((x, y))

    print("coordinates =", coordinates)
    # 假设已经获取到的像素点坐标列表
    # coordinates = [(150, 300), (151, 301), (160, 310), (300, 400), ...]  # 替换为实际的坐标列表

    # Step 1: 获取坐标范围
    x_coords = [coord[0] for coord in coordinates]
    y_coords = [coord[1] for coord in coordinates]

    min_x, max_x = min(x_coords), max(x_coords)
    min_y, max_y = min(y_coords), max(y_coords)

    # 根据坐标范围创建一个空白图像
    height_t, width_t = max_y - min_y + 1, max_x - min_x + 1
    binary_image = np.zeros((height_t, width_t), dtype=np.uint8)

    # Step 2: 映射坐标到二值图像
    for x, y in coordinates:
        mapped_x, mapped_y = x - min_x, y - min_y  # 映射到图像坐标
        binary_image[mapped_y, mapped_x] = 255

    # Step 3: 提取轮廓
    contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 提取最大的轮廓
    if contours:
        largest_contour = max(contours, key=cv2.contourArea)
        # 将轮廓映射回原坐标
        contour_coordinates = [(point[0][0] + min_x, point[0][1] + min_y) for point in largest_contour]
        print("提取到的轮廓坐标：", contour_coordinates)
    else:
        print("未检测到任何轮廓！")
        
    return contour_coordinates, width, height
        
def draw_contour_with_opencv(contour_coordinates, original_width, original_height):
    # 创建一个空白图像（黑色背景）
    # contour_image = np.zeros((original_height, original_width, 3), dtype=np.uint8)

    # 将轮廓坐标转为 OpenCV 的格式
    # contour_points = np.array(contour_coordinates, dtype=np.int32).reshape((-1, 1, 2))

    # 绘制轮廓
    # cv2.drawContours(contour_image, [contour_points], -1, (0, 255, 0), thickness=2)  # 绿色线条

    # 显示图像
    # cv2.imshow("Contour Visualization", contour_image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    x_range = (0, original_width)
    y_range = (0, original_height)
    figure_show(contour_coordinates, x_range, y_range)

if __name__ == '__main__':
    
    # pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\samples\2024-12-04_17-34-58.jpg" # 黑色
    # pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\samples\2024-12-04_18-25-02.jpg" # 黑色+白点 (785.2352941176471, 600.2352941176471) √ 灰度处理完后  (786.0409356725146, 600.9590643274854) √
    
    
    # pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\samples\2024-12-04_16-31-02.jpg" # 白色+红点 (1032.2172284644196, 434.9737827715356) √
    # pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\white_red.jpg" # 白色+红点 (783.6781609195402, 319.02298850574715) √ 灰度处理完后  (781.1304347826087, 319.19565217391306) √
    # pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\samples\2024-12-04_16-48-37.jpg" # 白框+黑色+白点
    
    
    # print("red_center, black_center =", getXY(pic_path))
    
    # output_image_path = image_convert_duibidu(pic_path)
    # output_image_path = r"C:\Users\iscas\Desktop\临时\慧眼\new_image.png"
    # red_center, black_center = getXY_white(output_image_path)
    # print("red_center, black_center =", red_center, black_center)
    
    pic_path = r"C:\Users\iscas\Desktop\临时\慧眼\origin.JPG"
    output_image_path = r"C:\Users\iscas\Desktop\临时\慧眼\current.png"
    # image_convert_duibidu(pic_path, output_image_path)
    sort_white_points(*get_white_points(output_image_path))
    # get_outer_points(get_white_points(output_image_path)[0])
    
    # draw_contour_with_opencv(*get_outer_points(output_image_path))